package com.techshine.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


public class HttpClintUtil {
       
	 /**
     * 根据地址获取网页信息html(post)
     * @param url
     * @return
     */
    public static Map<String,Object> getUrlStrings(String url,Map<String,String> headers){
 	String returnstr=null;
 	String encode = "utf-8";
 	String content = null;  
 	Map<String,Object> map =null;
    DefaultHttpClient httpclient = new DefaultHttpClient();  
 	//创建httpclient对象
		CloseableHttpClient client = HttpClients.createDefault();
		//以get方式请求url
//		HttpGet httpget= new HttpGet(url);
		HttpPost httpPost = new HttpPost(url);
		//设置 header  
		Header headerss[] = buildHeader(headers);  
        if(headerss != null && headerss.length > 0){  
    	   httpPost.setHeaders(headerss);  
        }  
        HttpResponse http_response;  
	    try {  
	        http_response = httpclient.execute(httpPost);  
	        HttpEntity entity = http_response.getEntity();  
	        content = EntityUtils.toString(entity, encode); 
	        map = (Map<String,Object>) JSON.parse(content);
	    } catch (Exception e) {  
	        e.printStackTrace();  
	    }finally {  
	    	httpPost.releaseConnection();  
	       }  
	       return map;
     }
    
    public static String postFileMultiPart(Map<String, String> header,String url, String imgUrl) throws ClientProtocolException, IOException{
		CloseableHttpClient httpclient = HttpClients.createDefault();
        
        try {
            // 创建httpget.    
        	HttpPost httppost = new HttpPost(url);
        	
        	if(header != null){
        		for(Entry<String, String> param : header.entrySet()){
            		httppost.addHeader(param.getKey(), param.getValue());
                }
        	}
        	
            //setConnectTimeout：设置连接超时时间，单位毫秒。setConnectionRequestTimeout：设置从connect Manager获取Connection 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。setSocketTimeout：请求获取数据的超时时间，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
            RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build();
            httppost.setConfig(defaultRequestConfig);
            
            System.out.println("executing request " + httppost.getURI());
            
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            File file = new File(imgUrl);
            multipartEntityBuilder.addBinaryBody("file",file);
            //multipartEntityBuilder.addPart("comment", new StringBody("This is comment", ContentType.TEXT_PLAIN));
            multipartEntityBuilder.addTextBody("comment", "this is comment");
//            for(Entry<String,ContentBody> param : reqParam.entrySet()){
//            	multipartEntityBuilder.addPart(param.getKey(), param.getValue());
//            }
            HttpEntity reqEntity = multipartEntityBuilder.build();
            httppost.setEntity(reqEntity);
            
            // 执行post请求.    
            CloseableHttpResponse response = httpclient.execute(httppost);
            
            System.out.println("got response");
            
            try {  
                // 获取响应实体    
                HttpEntity entity = response.getEntity();  
                //System.out.println("--------------------------------------");  
                // 打印响应状态    
                //System.out.println(response.getStatusLine());  
                if (entity != null) {  
                    // 打印响应内容长度    
                    //System.out.println("Response content length: " + entity.getContentLength());  
                    // 打印响应内容
                	return EntityUtils.toString(entity,Charset.forName("UTF-8"));
                }
                //System.out.println("------------------------------------");  
            } finally {  
                response.close();
                
            }
        } finally {  
            // 关闭连接,释放资源    
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }
        return null;
	}
    
    /**
     * 根据地址获取网页信息html(GET)
     * @param url
     * @return
     */
    public static Map<String,Object> getUrlStringsGET(String url,Map<String,String> headers){
    	String returnstr=null;
    	String encode = "utf-8";
    	String content = null;  
    	Map<String,Object> map =null;
    	DefaultHttpClient httpclient = new DefaultHttpClient();  
    	//创建httpclient对象
    	CloseableHttpClient client = HttpClients.createDefault();
    	//以get方式请求url
		HttpGet httpget= new HttpGet(url);
//    	HttpPost httpPost = new HttpPost(url);
    	//设置 header  
    	Header headerss[] = buildHeader(headers);  
    	if(headerss != null && headerss.length > 0){  
    		httpget.setHeaders(headerss);  
    	}  
    	HttpResponse http_response;  
    	try {  
    		http_response = httpclient.execute(httpget);  
    		HttpEntity entity = http_response.getEntity();  
    		content = EntityUtils.toString(entity, encode);  
    		map = (Map<String,Object>) JSON.parse(content);
    		System.out.println(entity);
    	} catch (Exception e) {  
    		e.printStackTrace();  
    	}finally {  
    		httpget.releaseConnection();  
    	}  
    	return map;
    }
    
    /** 
     * 组装请求头 
     * @param params 
     * @return 
     */  
       public static Header[] buildHeader(Map<String,String> params){  
        Header[] headers = null;  
        if(params != null && params.size() > 0){  
            headers = new BasicHeader[params.size()];  
            int i  = 0;  
            for (Entry<String, String> entry:params.entrySet()) {
                headers[i] = new BasicHeader(entry.getKey(),entry.getValue());
                i++;
            }
        }
        return headers;
       }
    /**
     * 根据地址获取网页信息html
     * @param url
     * @return
     */
    public static Map<String,Object> getUrlString(String url){
    	String returnstr=null;
    	//创建httpclient对象
    	CloseableHttpClient client = HttpClients.createDefault();
    	//以get方式请求url
//		HttpGet httpget= new HttpGet(url);
    	HttpPost httpPost = new HttpPost(url);
    	Map<String,Object> map =null;
    	try {
    		//得到response对象
    		CloseableHttpResponse response = client.execute(httpPost);
    		//返回码
    		int statusCode = response.getStatusLine().getStatusCode();
    		//200正常访问
    		if (statusCode ==HttpStatus.SC_OK) {
    			HttpEntity entity = response.getEntity();
    			returnstr= EntityUtils.toString(entity,"utf-8");
    			map = (Map<String,Object>) JSON.parse(returnstr);
    		}
    	}  catch (Exception e) {
    		e.printStackTrace();
    	}finally {
    		try {
    			client.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    	return map;
    }
    /**
     * 根据地址获取网页信息html
     * @param url
     * @return
     */
    public static Map<String,Object> getUrlStringGet(String url){
    	String returnstr=null;
    	//创建httpclient对象
    	CloseableHttpClient client = HttpClients.createDefault();
    	//以get方式请求url
		HttpGet httpget= new HttpGet(url);
    	Map<String,Object> map =null;
    	try {
    		//得到response对象
    		CloseableHttpResponse response = client.execute(httpget);
    		//返回码
    		int statusCode = response.getStatusLine().getStatusCode();
    		//200正常访问
    		if (statusCode ==HttpStatus.SC_OK) {
    			HttpEntity entity = response.getEntity();
    			returnstr= EntityUtils.toString(entity,"utf-8");
    			map = (Map<String,Object>) JSON.parse(returnstr);
    		}
    	}  catch (Exception e) {
    		e.printStackTrace();
    	}finally {
    		try {
    			client.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    	return map;
    }
    //get请求
    public static com.alibaba.fastjson.JSONObject doGet(String requestUrl) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String responseContent  = null;
        com.alibaba.fastjson.JSONObject result = null;
        try {
            //创建Get请求，
            HttpGet httpGet = new HttpGet(requestUrl);
            //执行Get请求，
            response = httpClient.execute(httpGet);
            //得到响应体
            HttpEntity entity = response.getEntity();
            //获取响应内容
            responseContent  = EntityUtils.toString(entity,"UTF-8");
            //转换为map
            result = JSON.parseObject(responseContent);
        } catch (IOException e) {
            System.out.println("HttpUtil=====Start");
            System.out.println("HttpUtil=====End");
        }
        return result;
    }


    /**
     * json参数方式POST提交
     * @param url
     * @param params
     * @return
     */
    public static Map<String, Object> doPost(String url, JSONObject params, Map<String,String> headers){
        String strResult = "";
        Map<String,Object> map =null;
        // 1. 获取默认的client实例
        CloseableHttpClient client = HttpClients.createDefault();
        // 2. 创建httppost实例
        HttpPost httpPost = new HttpPost(url);
        Header headerss[] = buildHeader(headers);
    	if(headerss != null && headerss.length > 0){
    		httpPost.setHeaders(headerss);
    	}
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8"); //添加请求头
        try {
            httpPost.setEntity(new StringEntity(params.toJSONString(),"utf-8"));
            CloseableHttpResponse resp = client.execute(httpPost);
            try {
                // 7. 获取响应entity
                HttpEntity respEntity = resp.getEntity();
                strResult = EntityUtils.toString(respEntity, "UTF-8");
                map = (Map<String,Object>) JSON.parse(strResult);
            } finally {
                resp.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }
    /**
     * json参数方式POST提交
     * @param url
     * @param params
     * @return
     */
    public static Map<String, Object> doPostJson(String url, StringEntity params,Map<String,String> headers){
    	String strResult = "";
    	Map<String,Object> map =null;
    	// 1. 获取默认的client实例
    	CloseableHttpClient client = HttpClients.createDefault();
    	// 2. 创建httppost实例
    	HttpPost httpPost = new HttpPost(url);
    	Header headerss[] = buildHeader(headers);
    	if(headerss != null && headerss.length > 0){
    		httpPost.setHeaders(headerss);
    	}
    	httpPost.addHeader("Content-Type", "application/json;charset=utf-8"); //添加请求头
    	try {
    		httpPost.setEntity(params);
    		CloseableHttpResponse resp = client.execute(httpPost);
    		try {
    			// 7. 获取响应entity
    			HttpEntity respEntity = resp.getEntity();
    			strResult = EntityUtils.toString(respEntity, "UTF-8");
    			map = (Map<String,Object>) JSON.parse(strResult);
    		} finally {
    			resp.close();
    		}
    	} catch (ClientProtocolException e) {
    		e.printStackTrace();
    	} catch (UnsupportedEncodingException e) {
    		e.printStackTrace();
    	} catch (IOException e) {
    		e.printStackTrace();
    	} finally {
    		try {
    			client.close();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    	return map;
    }
	/**
	 * json参数方式POST提交实体类
	 * @param url
	 * @param params
	 * @return
	 */
	public static Map<String, Object> doPostJsonEntity(String url, Object myclass,Map<String,String> headers){
		String strResult = "";
		Map<String,Object> map =null;
		// 1. 获取默认的client实例
		CloseableHttpClient client = HttpClients.createDefault();
		// 2. 创建httppost实例
		HttpPost httpPost = new HttpPost(url);
		Header headerss[] = buildHeader(headers);
		if(headerss != null && headerss.length > 0){
			httpPost.setHeaders(headerss);
		}

		String jsonSting = JSON.toJSONString(myclass);
		StringEntity entity = new StringEntity(jsonSting, "UTF-8");

		httpPost.addHeader("Content-Type", "application/json;charset=utf-8"); //添加请求头
		try {
			httpPost.setEntity(entity);
			CloseableHttpResponse resp = client.execute(httpPost);
			try {
				// 7. 获取响应entity
				HttpEntity respEntity = resp.getEntity();
				strResult = EntityUtils.toString(respEntity, "UTF-8");
				map = (Map<String,Object>) JSON.parse(strResult);
			} finally {
				resp.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				client.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return map;
	}
    /**
     * 根据地址获取网页信息html(GET)
     * @param url
     * @return
     */
    public static Map<String,Object> getUrlStringsGETAuthorization(String url,Map<String,String> headers){
    	String returnstr=null;
    	String encode = "utf-8";
    	String content = null;
    	Map<String,Object> map =null;
    	DefaultHttpClient httpclient = new DefaultHttpClient();
    	//创建httpclient对象
    	CloseableHttpClient client = HttpClients.createDefault();
    	//以get方式请求url
    	HttpGet httpget= new HttpGet(url);
    	//设置 header
    	Header headerss[] = buildHeader(headers);
    	if(headerss != null && headerss.length > 0){
    		httpget.setHeaders(headerss);
    	}
    	httpget.addHeader("Content-Type", "application/json;charset=utf-8"); //添加请求头
    	HttpResponse http_response;
    	try {
    		http_response = httpclient.execute(httpget);
    		HttpEntity entity = http_response.getEntity();
    		content = EntityUtils.toString(entity, encode);
    		map = (Map<String,Object>) JSON.parse(content);
    		System.out.println(entity);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}finally {
    		httpget.releaseConnection();
    	}
    	return map;
    }
    /**
     * 根据地址获取网页信息html(POST)
     * @param url
     * @return
     */
    public static Map<String,Object> getUrlStringsPOSTAuthorization(String url,Map<String,String> headers){
    	String returnstr=null;
    	String encode = "utf-8";
    	String content = null;
    	Map<String,Object> map =null;
    	DefaultHttpClient httpclient = new DefaultHttpClient();
    	//创建httpclient对象
    	CloseableHttpClient client = HttpClients.createDefault();
    	//以POST方式请求url
    	HttpPost httpPost= new HttpPost(url);
    	//设置 header
    	Header headerss[] = buildHeader(headers);
    	if(headerss != null && headerss.length > 0){
    		httpPost.setHeaders(headerss);
    	}
    	httpPost.addHeader("Content-Type", "application/json;charset=utf-8"); //添加请求头
    	HttpResponse http_response;
    	try {
    		http_response = httpclient.execute(httpPost);
    		HttpEntity entity = http_response.getEntity();
    		content = EntityUtils.toString(entity, encode);
    		map = (Map<String,Object>) JSON.parse(content);
    		System.out.println(entity);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}finally {
    		httpPost.releaseConnection();
    	}
    	return map;
    }



    public static String mapPost(String url, Map<String,Object> map,Map<String,String> headers){
    	CloseableHttpClient httpClient = null;
    	HttpPost httpPost= new HttpPost(url);
    	String result = null;

    	//设置 header
		Header headerss[] = buildHeader(headers);
	    if(headerss != null && headerss.length > 0){
	    	httpPost.setHeaders(headerss);
	    }
    	try{
    		httpClient = HttpClients.createDefault();
//    		httpPost = new HttpPost(url);
    		//设置参数
    		List<NameValuePair> list = new ArrayList<NameValuePair>();
    		Iterator iterator = map.entrySet().iterator();
    		while(iterator.hasNext()){
    			Entry<String,String> elem = (Entry<String, String>) iterator.next();
    			list.add(new BasicNameValuePair(elem.getKey(),String.valueOf(elem.getValue())));
    		}
    		if(list.size() > 0){
    			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"utf-8");
    			httpPost.setEntity(entity);
    		}
    		HttpResponse response = httpClient.execute(httpPost);
    		if(response != null){
    			HttpEntity resEntity = response.getEntity();
    			if(resEntity != null){
    				result = EntityUtils.toString(resEntity,"utf-8");
    			}
    		}
    	}catch(Exception ex){
    		ex.printStackTrace();
		}
    		return result;
	}
    
    
//以下是获取微信用户openid所需代码
    
    private static class SingletonHolder{
        private final static  HttpClintUtil INSTANCE=new HttpClintUtil();
    }
 
    private HttpClintUtil(){}
 
    public static HttpClintUtil getInstance(){
        return SingletonHolder.INSTANCE;
    }
 
    public  String get(String url){
        CharsetHandler handler = new CharsetHandler("UTF-8");
        CloseableHttpClient client = null;
        try {
            HttpGet httpget = new HttpGet(new URI(url));
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            client= httpClientBuilder.build();
            client = (CloseableHttpClient) wrapClient(client);
            return client.execute(httpget, handler);
        } catch (Exception e) {
            //e.printStackTrace();
            return "";
        }finally {
            try {
                if(client!=null){
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    public static String post(String url, String params,String contentType)
    {
 
        //创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        //HttpClient
        CloseableHttpClient client = httpClientBuilder.build();
        client = (CloseableHttpClient) wrapClient(client);
 
 
        HttpPost post = new HttpPost(url);
        CloseableHttpResponse res = null;
        try
        {
            StringEntity s = new StringEntity(params,"UTF-8");
            if(StringUtils.isBlank(contentType)){
                s.setContentType("application/json");
            }
            s.setContentType(contentType);
            s.setContentEncoding("utf-8");
            post.setEntity(s);
            res = client.execute(post);
            HttpEntity entity = res.getEntity();
            return EntityUtils.toString(entity, "utf-8");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        } finally {
            try {
                res.close();
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
 
    public static String post(String urlStr,String xmlInfo) {
        String line1 = "";
        try {
            URL url = new URL(urlStr);
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            //con.setRequestProperty("Pragma:", "no-cache");
            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Content-Type", "text/xml");
 
            OutputStreamWriter out = new OutputStreamWriter(con
                    .getOutputStream());
            out.write(new String(xmlInfo.getBytes("utf-8")));
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(con
                    .getInputStream()));
            String line = "";
            for (line = br.readLine(); line != null; line = br.readLine()) {
                line1+=line;
            }
            return new String(line1.getBytes(),"utf-8");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
 
    private class CharsetHandler implements ResponseHandler<String> {
        private String charset;
 
        public CharsetHandler(String charset) {
            this.charset = charset;
        }
 
        public String handleResponse(HttpResponse response)
                throws ClientProtocolException, IOException {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(),
                        statusLine.getReasonPhrase());
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                if (!StringUtils.isBlank(charset)) {
                    return EntityUtils.toString(entity, charset);
                } else {
                    return EntityUtils.toString(entity);
                }
            } else {
                return null;
            }
        }
    }
 
    private static  HttpClient wrapClient(HttpClient base) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLSv1");
            X509TrustManager tm = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] xcs,
                                               String string) throws CertificateException {
                }
 
                public void checkServerTrusted(X509Certificate[] xcs,
                                               String string) throws CertificateException {
                }
 
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new String[] { "TLSv1" }, null,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            return httpclient;
 
        } catch (Exception ex) {
            return null;
        }
    }
}
